package com.bolins.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileCase {

	public static void main(String[] args) {
		try {

			File f = new File("d:\\1.txt");
			FileInputStream fis = new FileInputStream(f);
			byte[] b = new byte[(int) f.length()];
			fis.read(b);
			for (int i = 0; i < b.length; i++) {
				System.out.print(b[i]);
			}

			System.out.println("\n\n");
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					f));
			BufferedReader br = new BufferedReader(read);
			String line = "";
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取文件内容
	 * 
	 * @param filePathAndName
	 *            String 读取文件路径
	 * @return String 文件中的内容
	 * 
	 *         InputStreamReader 是字节流通向字符流的桥梁
	 */
	public static String readFile(String filePathAndName) {

		String fileContent = "";
		try {
			File f = new File(filePathAndName);
			if (f.isFile() && f.exists()) {

				InputStreamReader read = new InputStreamReader(
						new FileInputStream(f), "gb2312");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {

					fileContent += line;

				}
				read.close();
			}

			System.out.println("fileContent:" + fileContent);
			FileCase.writeFile("kkkkkkkkk.txt", fileContent);

		} catch (Exception e) {
			System.out.println("读取文件内容操作出错");
			e.printStackTrace();
		}
		return fileContent;
	}

	/**
	 * 写文件
	 * 
	 * @param filePathAndName
	 *            String 写文件路径
	 * @param fileContent
	 *            String 需要写入的内容
	 * 
	 *            OutputStreamWriter 是字符流通向字节流的桥梁
	 */

	public static void writeFile(String filePathAndName, String fileContent) {
		try {

			File f = new File(filePathAndName);
			if (!f.exists()) {

				f.createNewFile();
			}

			OutputStreamWriter write = new OutputStreamWriter(
					new FileOutputStream(f), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(fileContent);
			writer.close();

		} catch (Exception e) {
			System.out.println("写文件内容操作出错");
			e.printStackTrace();
		}
	}

}
